from cozepy import COZE_CN_BASE_URL, Coze, TokenAuth, Stream, WorkflowEvent, WorkflowEventType

def run_coze_workflow(user_input: str, workflow_id: str, api_token: str, base_url: str = COZE_CN_BASE_URL):
    coze = Coze(auth=TokenAuth(token=api_token), base_url=base_url)
    result = []

    def handle_workflow_iterator(stream: Stream[WorkflowEvent]):
        for event in stream:
            if event.event == WorkflowEventType.MESSAGE:
                result.append(event.message.content)  # 修改点：提取 .content 字符串
            elif event.event == WorkflowEventType.ERROR:
                raise Exception(f"发生错误: {event.error}")
            elif event.event == WorkflowEventType.INTERRUPT:
                handle_workflow_iterator(
                    coze.workflows.runs.resume(
                        workflow_id=workflow_id,
                        event_id=event.interrupt.interrupt_data.event_id,
                        resume_data="hey",
                        interrupt_type=event.interrupt.interrupt_data.type,
                    )
                )

    handle_workflow_iterator(
        coze.workflows.runs.stream(
            workflow_id=workflow_id,
            parameters={"input": user_input}
        )
    )

    return "".join(result) if result else None

# 使用示例
if __name__ == "__main__":
    # 配置参数
    WORKFLOW_ID = "7524554138333528064"   #picture_style,风格为美漫
    WORKFLOW_ID1 = "7524555233420181523"  #style3，风格为粘土
    WORKFLOW_ID2 = "7524554969475940367"  #style2，风格为搞笑涂鸦
    WORKFLOW_ID3 = "7524554698281975818"  #style1，风格为工笔画
    API_TOKEN = "pat_JzRhQ45cdVnjzwjPLHCJF1MmYI06vuCCFaaFBW65WkBCB4l9lvWhtJWOMxd3LOM1"

    # 运行工作流
    a=run_coze_workflow("https://s.coze.cn/t/LqKzISsM2wQ/",workflow_id=WORKFLOW_ID2, api_token=API_TOKEN)
    print(a)